package jdbc.dao;


import jdbc.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public User selectById(String id){
        List<User> list = jdbcTemplate.query("select id,name from user where id = ?", new Object[]{id}, new BeanPropertyRowMapper(User.class));
        if(list!=null && list.size()>0){
            User user = list.get(0);
            return user;
        }else{
            return null;
        }
    }

    public List<User> selectList(){
        List<User> list = jdbcTemplate.query("select id,name from user", new Object[]{}, new BeanPropertyRowMapper(User.class));
        if(list!=null && list.size()>0){
            return list;
        }else{
            return null;
        }
    }

    public int insert(User user){
        return jdbcTemplate.update("insert into user(id, name) values(?, ?)", user.getId(),user.getName());
    }

    public int updateById(User user){
        return jdbcTemplate.update("UPDATE user SET name = ? WHERE id=?", user.getName(),user.getId());
    }

    public int deleteById(String id){
        return jdbcTemplate.update("DELETE from user where id=?",id);
    }

}
